export class Dialogue{
  constructor(npc){
    this.npc = npc;

    this.groups = [];
  }

  clear(){
    this.groups = [];
  }

  define(group){
    this.groups.push(group(this.npc));
  }

  find(name){
    return this.groups.find(item => item.name === name);
  }

  group(name, config = {}){
    return new DialogueGroup(this.npc, name, config);
  }

  showGroups(groups){
    // 当npc对玩家的好感为仇恨时，将会拒绝对话
    if(this.npc.people.data.favor < -1000){
      return [];
    }

    return groups.filter(item => item.isOptional(this.npc));
  }
}

export class DialogueGroup{
  constructor(npc, name, {
    // 在指定世界定位中可显示
    worldPos = false,
    // 在指定小地图定位中可显示
    mapPos = false,
    // 任务相关配置
    task = false,
    // 是否需要特定的对话
    dialogue = false,
    // 是否显示在多序列中
    show = true
  }){
    this.npc = npc;
    this.name = name;
    
    this.worldPos = worldPos;
    this.mapPos = mapPos;
    this.task = task;
    this.dialogue = dialogue;
    this.show = show;

    this.dialogues = [];
  }

  getName(){
    return this.npc.storeId + '-' + this.name;
  }

  section(me, message, name){
    if(typeof me !== 'string'){
      this.dialogues.push(me);

      return me;
    } else {
      let dialogue = new DialogueSection(me, message, name);

      this.dialogues.push(dialogue);
      return dialogue;
    }
  }

  saveOnce(){
    this.npc.root.worldData.dialogues.push(this.getName());
    this.npc.root.saveWorldData();
  }

  isOptional(npc){
    let flag = true;

    if(!this.show) return false;

    // 判断是否已经选择过
    let isSelected = npc.root.worldData.dialogues.find(item => {
      return item === this.getName();
    })
    if(isSelected) flag = false;

    if(this.worldPos){
      if(npc.people.data.worldPos[0] !== this.worldPos[0] || npc.people.data.worldPos[1] !== this.worldPos[1]) flag = false;
    }

    if(this.mapPos){
      if(npc.people.data.mapPos[0] !== this.mapPos[0] || npc.people.data.mapPos[1] !== this.mapPos[1]) flag = false;
    }

    // 判断是否需要特定对话
    if(this.dialogue){
      let findDialogue = this.npc.root.worldData.dialogues.find(dialogue => {
        return dialogue == this.dialogue
      })
      if(!findDialogue) {
        flag = false;
      }
    }

    if(this.task){
      if(this.task.pick !== undefined){
        let pickTask = npc.root.task.isPickTask(this.task.id);
        let isPick = pickTask ? !pickTask.complete : false;

        if(isPick !== this.task.pick) flag = false;
      }
    }

    return flag;
  }
}

export class DialogueSection{
  constructor(me, message){
    this.me = me;
    this.message = message;
  }

  // 结束对话
  closeDialogue(){
    
  }

  // 点击这个选项触发
  click(){

  }
}